package com.toman.ui.work.workplan;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseProductReportEntity;
import com.toman.JavaBean.ReceiveSendworkOrderDto;
import com.toman.R;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class SubmitPlanEditActivity extends ToolBarActivity {

    @BindView(R.id.tv_completed_count4)
    TextView tvCompletedCount4;
    @BindView(R.id.tv_qualified_count4)
    TextView tvQualifiedCount4;
    @BindView(R.id.tv_scrapped_count4)
    TextView tvScrappedCount4;
    @BindView(R.id.tv_waste_count4)
    TextView tvWasteCount4;
    @BindView(R.id.tv_reuse_count4)
    TextView tvReuseCount4;
    @BindView(R.id.tv_remake_count4)
    TextView tvRemakeCount4;
    @BindView(R.id.rl_progress4)
    RelativeLayout rlProgress4;
    @BindView(R.id.tv_check_man)
    TextView tvCheckMan;
    @BindView(R.id.rl_check)
    RelativeLayout rlCheck;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.rl_check_time)
    RelativeLayout rlCheckTime;
    @BindView(R.id.ll_audit)
    LinearLayout llAudit;
    @BindView(R.id.rl_more)
    RelativeLayout rlMore;
    @BindView(R.id.tv_completed_count3)
    TextView tvCompletedCount3;
    @BindView(R.id.tv_qualified_count3)
    TextView tvQualifiedCount3;
    @BindView(R.id.tv_scrapped_count3)
    TextView tvScrappedCount3;
    @BindView(R.id.tv_waste_count3)
    TextView tvWasteCount3;
    @BindView(R.id.tv_reuse_count3)
    TextView tvReuseCount3;
    @BindView(R.id.tv_remake_count3)
    TextView tvRemakeCount3;
    @BindView(R.id.rl_progress3)
    RelativeLayout rlProgress3;
    @BindView(R.id.et_completed_count)
    EditText etCompletedCount;
    @BindView(R.id.et_qualified_count)
    EditText etQualifiedCount;
    @BindView(R.id.et_scrapped_count)
    EditText etScrappedCount;
    @BindView(R.id.et_waste_count)
    EditText etWasteCount;
    @BindView(R.id.et_remake_count)
    EditText etRemakeCount;
    @BindView(R.id.et_reuse_count)
    EditText etReuseCount;
    @BindView(R.id.ll_sumit_more_count)
    LinearLayout llSumitMoreCount;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_order_remark_name)
    TextView tvOrderRemarkName;
    @BindView(R.id.et_order_remark)
    ClearEditText etOrderRemark;
    @BindView(R.id.tv_create_man)
    TextView tvCreateMan;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.ll_create)
    LinearLayout llCreate;
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.tv_beltline)
    TextView tvBeltline;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.tv_beltline_planoutput)
    TextView tvBeltlinePlanoutput;
    @BindView(R.id.ll_more1)
    LinearLayout llMore1;
    @BindView(R.id.ll_1)
    LinearLayout ll1;
    @BindView(R.id.tv_edit_man)
    TextView tvEditMan;
    @BindView(R.id.tv_edit_time)
    TextView tvEditTime;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    Camera camera;
    DeviceHouseProductReportEntity bean = new DeviceHouseProductReportEntity();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_plan_edit);
        ButterKnife.bind(this);
        initIntent();
        initView();
    }

    private void initIntent() {
        bean = (DeviceHouseProductReportEntity) getIntent().getSerializableExtra("bean");
        status = getIntent().getStringExtra("status");

    }

    private void initView() {
        String url[] = new String[bean.getImages().size()];
        for (int i = 0; i < url.length; i++) {
            url[i] = bean.getImages().get(i).getImagePath();

        }
        camera = ViewUtil.createPhoto("产品图片", url, camera, this, ll, true);

        ViewUtil.unedit(etOrderRemark);
        baseEnum = BaseEnum.WORKSHOPSUBMIT;
        initToolBar(baseEnum.detail());
        String[] item = new String[]{bean.getDepartmentName(), bean.getBeltlineName(), bean.getDay(), bean.getBeltlinePlanOutput(),bean.getDescription()};//直接初始化
        ViewUtil.setText(item, tvDep, tvBeltline, tvDay, tvBeltlinePlanoutput,etOrderRemark);
        if (bean.getAuditStatus().equals("0")) {
            llAudit.setVisibility(View.GONE);
        }
        if (bean.getAuditStatus().equals("1")) {
            tvQualifiedCount4.setText("合格数量:" + bean.getVerifyQualifiedCount() + "");
            tvScrappedCount4.setText("报废数量:" + bean.getVerifyBrokenCount() + "");
            tvCompletedCount4.setText("完工数量:" + bean.getVerifyFinishCount() + "");
            tvWasteCount4.setText("料废数量:" + bean.getVerifyWasteCount() + "");
            tvRemakeCount4.setText("返工数量:" + bean.getVerifyRemadeCount() + "");
            tvReuseCount4.setText("回用数量:" + bean.getVerifyReuseCount() + "");
            tvCheckMan.setText(bean.getAuditUserName());
            tvCheckTime.setText(bean.getAuditTime());
        }
        Object[] str = new Object[]{bean.getFinishCount(), bean.getQualifiedCount(), bean.getRemadeCount(), bean.getReuseCount(), bean.getBrokenCount(), bean.getWasteCount()};
        ViewUtil.setText(str, etCompletedCount, etQualifiedCount, etRemakeCount, etReuseCount, etScrappedCount, etWasteCount);
        tvCreateMan.setText(bean.getCreateUserName());
        tvCreateTime.setText(bean.getCreateTime());
        tvEditMan.setText(bean.getUpdateUserName());
        tvEditTime.setText(bean.getUpdateTime());
        tvQualifiedCount3.setText("合格数量:" + bean.getQualifiedCount() + "");
        tvScrappedCount3.setText("报废数量:" + bean.getBrokenCount() + "");
        tvCompletedCount3.setText("完工数量:" + bean.getFinishCount() + "");
        tvWasteCount3.setText("料废数量:" + bean.getWasteCount() + "");
        tvRemakeCount3.setText("返工数量:" + bean.getRemadeCount() + "");
        tvReuseCount3.setText("回用数量:" + bean.getReuseCount() + "");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (status.equals("1")) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            ViewUtil.gone(rlProgress3);
                            ViewUtil.visible(llSumitMoreCount);
                            ViewUtil.edit(etOrderRemark);
                            camera.init(false);
//                            修改数量状态

                        } else {
                            add();
                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void add() {
        String[] item = new String[]{"确认完工数量", "确认合格数量"};//直接初始化

        if (ViewUtil.isNull(this, item, etCompletedCount, etQualifiedCount)
                ) {
            return;
        }
        if (ViewUtil.compareString(this, item, etCompletedCount, etQualifiedCount)
                ) {
            return;
        }

        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");

        List<String> list = camera.getCompressUrl();
        List<File> files = new ArrayList<>();
        for (String path : list) {
            File file = new File(path);
            files.add(file);
        }
        OkHttpUtils
                .post(NewBaseUrl.devicehouseproductreport_update)
                .headers("token", token)
                .headers("Content-Type", "multipart/form-data")
                .addFileParams("file", ViewUtil.getFiles(camera))
                .params("id", bean.getId() + "")

                .params("departmentId", bean.getDepartmentId() + "")
                .params("beltlineId", bean.getBeltlineId() + "")
                .params("day", bean.getDay() + "")
                .params("finishCount", etCompletedCount.getText().toString())
                .params("qualifiedCount", etQualifiedCount.getText().toString())
                .params("brokenCount", etScrappedCount.getText().toString())
                .params("wasteCount", etWasteCount.getText().toString())
                .params("remadeCount", etRemakeCount.getText().toString())
                .params("reuseCount", etReuseCount.getText().toString())
                .params("description", etOrderRemark.getText().toString())
                .params("deleteUrls", camera.getDeleteUrlNew())
                .execute(new StringCallback() {
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        Toast.makeText(getApplicationContext(), "请检查您的网络连接!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            dialog.dismiss();

                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }
                        dialog.dismiss();

                    }
                });

    }

}
